package com.basil.gym.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.basil.gym.constants.RedisConstants;
import com.basil.gym.pojo.entity.Course;
import com.basil.gym.pojo.query.CourseQuery;
import com.basil.gym.service.ICourseService;
import com.basil.gym.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Basil
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private ICourseService courseService;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/list")
    public Result list(){
        return Result.ok(courseService.list());
    }
    @GetMapping("/selectByPage")
    public Result selectByPage(CourseQuery courseQuery){
        System.out.println(courseQuery);
        IPage<Course> page = courseService.selectByPage(courseQuery);
        return Result.ok(page);
    }

    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Course course = courseService.getById(id);
        return Result.ok(course);
    }

    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        courseService.removeById(id);
        return Result.ok("删除成功");
    }

    @DeleteMapping("/deleteAll/{ids}")
    public Result deleteAll(@PathVariable Integer[] ids) {
        courseService.removeBatchByIds(Arrays.asList(ids));
        return Result.ok("批量删除成功");
    }

    @PutMapping("/update")
    public Result update(@RequestBody Course course) {
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, course.getImage());
        courseService.updateById(course);
        return Result.ok("修改成功");
    }

    @PostMapping("/add")
    public Result add(@RequestBody Course course) {
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE_TO_DB, course.getImage());
        courseService.save(course);
        return Result.ok("添加成功");
    }

    //导出
    @GetMapping("/exportExcel")
    public void exportData(HttpServletResponse response) {
        courseService.exportExcel(response);
    }

    //导入
    @PostMapping("/importExcel")
    public Result importExcel(MultipartFile file) {
        courseService.importExcel(file);
        return Result.ok("导入成功");
    }

}

